// whitespace regex to avoid creating every time
var re = /\s+/;

/**
 * Wrap `el` in a `ClassList`.
 *
 * @param {Element} el
 * @return {ClassList}
 * @api public
 */

module.exports = function(el){
    return new ClassList(el);
};

/**
 * Initialize a new ClassList for `el`.
 *
 * @param {Element} el
 * @api private
 */

function ClassList(el) {
    this.el = el;
    this.list = el.classList;
}

/**
 * Add class `name` if not already present.
 *
 * @param {String} name
 * @return {ClassList}
 * @api public
 */

ClassList.prototype.add = function(name){
    // classList
    if (this.list) {
        this.list.add(name);
        return this;
    }

    // fallback
    var arr = this.array();
    var i = arr.indexOf(name);
    if (!~i) {
        arr.push(name);
    }
    this.el.className = arr.join(' ');
    return this;
};

/**
 * Remove class `name` when present.
 *
 * @param {String} name
 * @return {ClassList}
 * @api public
 */

ClassList.prototype.remove = function(name){
    // classList
    if (this.list) {
        this.list.remove(name);
        return this;
    }

    // fallback
    var arr = this.array();
    var i = arr.indexOf(name);
    if (~i) {
        arr.splice(i, 1);
    }
    this.el.className = arr.join(' ');
    return this;
};

/**
 * Toggle class `name`.
 *
 * @param {String} name
 * @return {ClassList}
 * @api public
 */

ClassList.prototype.toggle = function(name){
    // classList
    if (this.list) {
        this.list.toggle(name);
        return this;
    }

    // fallback
    if (this.has(name)) {
        return this.remove(name);
    }

    return this.add(name);
};

/**
 * Return an array of classes.
 *
 * @return {Array}
 * @api public
 */

ClassList.prototype.array = function(){
    var arr = this.el.className.split(re);
    if ('' === arr[0]) {
        arr.pop();
    }
    return arr;
};

/**
 * Check if class `name` is present.
 *
 * @param {String} name
 * @return {ClassList}
 * @api public
 */

ClassList.prototype.has = function(name){
    return this.list
        ? this.list.contains(name)
        : !! ~this.array().indexOf(name);
};